package cc.magicjson.data.operation.router.db.router;

import cc.magicjson.data.operation.router.db.datasource.DataSourceHolder;
import org.springframework.boot.actuate.endpoint.OperationType;

import javax.sql.DataSource;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class OperationRouter {
    private final boolean enableSlaveWrite;

    public OperationRouter(boolean enableSlaveWrite) {
        this.enableSlaveWrite = enableSlaveWrite;
    }

    public OperationType determineOperationType(Method method) {
        if (method.getName().startsWith("find") || method.getName().startsWith("select")) {
            return OperationType.READ;
        }
        return OperationType.WRITE;
    }

    public List<DataSource> determineTargetDataSources(OperationType operationType) {
        List<DataSource> targetDataSources = new ArrayList<>();
        targetDataSources.add(DataSourceHolder.getMaster());

        if (enableSlaveWrite && operationType == OperationType.WRITE) {
            targetDataSources.add(DataSourceHolder.getSlave());
        }

        return targetDataSources;
    }
}
